//
//  EditDetailViewController.m
//  Runone
//
//  Created by runone02 on 16/11/23.
//  Copyright © 2016年 runone. All rights reserved.
//  进行中事件

#import "EditDetailViewController.h"
#import "RequestGinsengModel.h"
#import "RequestHelper.h"
#import "EventDetailModel.h"
#import "MJExtension.h"
#import "SVProgressHUD.h"
#import "ConEventDetailInfo.h"
#import "EventDealList.h"
#import "ParModel.h"
#import "ConstructionEventDetailInfo.h"
#import "ROImagePickViewController.h"
#import "AJPhotoPickerViewController.h"
#import "AJPhotoBrowserViewController.h"
#import "LittleVideoViewController.h"
#import <AVKit/AVKit.h>
#import <AVFoundation/AVFoundation.h>
#import <AssetsLibrary/AssetsLibrary.h>
#import "BCNetAPIClient.h"

@interface EditDetailViewController ()<UITextViewDelegate, UIAlertViewDelegate, LittleVideoDelegate,AJPhotoPickerProtocol,AJPhotoBrowserDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate> {
    AVPlayer *_player;
    AVPlayerItem *_playItem;
    AVPlayerLayer *_playerLayer;
    AVPlayerLayer *_fullPlayer;
    BOOL _isPlaying;
}
// **************************************** -UI- ****************************************
@property (weak, nonatomic) IBOutlet UITextField *unitsLabel;         //施工单位
@property (weak, nonatomic) IBOutlet UITextField *headerTF;           //负责人
@property (weak, nonatomic) IBOutlet UITextField *contactTF;          //联系人
@property (weak, nonatomic) IBOutlet UITextField *planBeginTimeTF;    //计划开始时间
@property (weak, nonatomic) IBOutlet UITextField *planEndTimeTF;      //计划结束时间
@property (weak, nonatomic) IBOutlet UITextField *beginPileTF;        //开始桩号
@property (weak, nonatomic) IBOutlet UITextField *beginPileDistanceTF;//开始桩号距离
@property (weak, nonatomic) IBOutlet UITextField *endPileTF;          //结束桩号
@property (weak, nonatomic) IBOutlet UITextField *endPileDistanceTF;  //结束桩号距离
@property (weak, nonatomic) IBOutlet UITextField *mainLineTF;         //主线 南 北
@property (weak, nonatomic) IBOutlet UIButton    *mainLineBtn;        //主线的按钮
@property (weak, nonatomic) IBOutlet UITextField *isMianLine;         //是否是主线
@property (weak, nonatomic) IBOutlet UITextField *isMainLineTF;
@property (weak, nonatomic) IBOutlet UIButton    *isMainLineBtn;      //是否是主线按钮
@property (weak, nonatomic) IBOutlet UITextField *RoadDirectionTF;    //方向
@property (weak, nonatomic) IBOutlet UITextView  *projectTF;          //施工项目
@property (weak, nonatomic) IBOutlet UITextView  *dealTF;             //施工处置
@property (weak, nonatomic) IBOutlet UIView *dealView;
@property (weak, nonatomic) IBOutlet UIScrollView *imageScrollView;
@property (weak, nonatomic) IBOutlet UIView *VideoV;

// **************************************** -请求数据- ****************************************
@property (nonatomic, strong) EventDetailModel *Model;


@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dealTFHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *dealViewHeight;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *containerViewH;


@property (nonatomic, strong) LittleVideoViewController *littleVideoVC;//拍摄小视频界面
@property (nonatomic, strong) NSURL *videoUrl;
@property (nonatomic, strong) NSMutableArray   *imageArray;
@property (nonatomic, strong) NSMutableArray   *originalImgArr;
@property (strong, nonatomic) NSMutableArray   *photos;
@end

@implementation EditDetailViewController

- (IBAction)ChooseImage:(UIButton *)sender {
    [self UpLoadPictures];
}
- (void) UpLoadPictures {
    if (self.originalImgArr.count >= 5) {
        [SVProgressHUD showErrorWithStatus:@"不能选择超过5张图"];
        return;
    }
    AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
    picker.maximumNumberOfSelection = 5;
    picker.multipleSelection        = YES;
    picker.assetsFilter             = [ALAssetsFilter allPhotos];
    picker.showEmptyGroups          = YES;
    picker.delegate                 = self;
    picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
        return YES;
    }];
    
    [self presentViewController:picker animated:YES completion:nil];
}

- (IBAction)CommitBtn:(id)sender {
    [self configCameraBtn];
}

-(void)configCameraBtn {
    //    [_Prompt alert:@"抱歉！暂时无法使用该功能"];
    [self cameraBtnClick];
}

- (void) cameraBtnClick {
    NSLog(@"这个照相机哦");
    LittleVideoViewController *vc = [[LittleVideoViewController alloc] init];
    vc.delegate = self;
    [self.navigationController presentViewController:vc animated:YES completion:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _photos = [[NSMutableArray alloc] init];
    [self configNaviABar];
    [self setUpUIDefaultConfig];
    [self requstData];
    [self setConfig];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
}
#pragma mark -按钮监听
#pragma mark - 提交数据
- (void) commitBtnClick {
    NSLog(@"提交");
    if (!(_dealTF.text.length > 0))  {
        [SVProgressHUD showErrorWithStatus:@"施工处置不能为空"];
        return;
    }
    [self postDataToServer];
}

- (void) cancleBtnClick {
    UIAlertView *showAlert=[[UIAlertView alloc] initWithTitle:nil message:@"是否确认结束该事件" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
    [showAlert show];
    
}

#pragma mark - 
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (buttonIndex == 0) {
        [alertView dismissWithClickedButtonIndex:0 animated:YES];
    }
    if (buttonIndex == 1) {
        if (_dealTF.text.length < 1) {
            [SVProgressHUD showErrorWithStatus:@"请在施工处置说明为何结束此事件"];
            return;
        }

        RequestGinsengModel *CancleConstructionEventDetailInfoModel =[[RequestGinsengModel alloc] init];
        CancleConstructionEventDetailInfoModel.URL         = GetEventDataURL;
        CancleConstructionEventDetailInfoModel.MethodName  = @"StopOrCancelConstructionEvent";
        CancleConstructionEventDetailInfoModel.DataValue   = [self dataValueString];
        CancleConstructionEventDetailInfoModel.UpdatedTime = @"";
        CancleConstructionEventDetailInfoModel.SystemCode  = @"GuangleHighway";

        [self requestTestUpdateImage:CancleConstructionEventDetailInfoModel Image:_originalImgArr];
    }
}

-(NSString *)cancleConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"IncidentUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}

#pragma  mark - UI默认的设置
- (void) setUpUIDefaultConfig {
    _unitsLabel.enabled               = NO;
    _headerTF.enabled                 = NO;
    _contactTF.enabled                = NO;
    _planEndTimeTF.enabled            = NO;
    _planBeginTimeTF.enabled          = NO;
    _beginPileTF.enabled              = NO;
    _beginPileDistanceTF.enabled      = NO;
    _endPileTF.enabled                = NO;
    _endPileDistanceTF.enabled        = NO;
    _mainLineTF.enabled               = NO;
    _isMainLineBtn.enabled            = NO;
    _isMainLineTF.enabled             = NO;
    _RoadDirectionTF.enabled          = NO;
    _projectTF.userInteractionEnabled = NO;
}

#pragma mark - 导航栏
- (void) configNaviABar {
    //右边view
    UIButton *commitBtn = [[UIButton alloc] init];
    [commitBtn setTitle:@"提交" forState:UIControlStateNormal];
    commitBtn.frame         = CGRectMake(0, 0, 40, 40);
    [commitBtn addTarget:self action:@selector(commitBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *commit = [[UIBarButtonItem alloc] initWithCustomView:commitBtn];
    
    UIButton *cancleBtn = [[UIButton alloc] init];
    [cancleBtn setTitle:@"结束" forState:UIControlStateNormal];
    cancleBtn.frame         = CGRectMake(0, 0, 40, 40);
    [cancleBtn addTarget:self action:@selector(cancleBtnClick) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *cancle = [[UIBarButtonItem alloc] initWithCustomView:cancleBtn];

    self.navigationItem.rightBarButtonItems = @[commit, cancle];
    //主标题
    UILabel *titleL               = [[UILabel alloc] init];
    titleL.text                   = @"进行中事件";
    titleL.frame                  = CGRectMake(0, 0, 150, 30);
    titleL.textAlignment          = NSTextAlignmentCenter;
    titleL.textColor              = [UIColor whiteColor];
    self.navigationItem.titleView = titleL;
}
#pragma mark - 请求数据
- (void) requstData {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *GetConstructionEventDetailInfo = [[RequestGinsengModel alloc] init];
    GetConstructionEventDetailInfo.URL         = GetEventDataURL;
    GetConstructionEventDetailInfo.DataValue   = [self getConstructDataValueStr:self.reportModel.IncidentUID];
    GetConstructionEventDetailInfo.UpdatedTime = @"";
    GetConstructionEventDetailInfo.SystemCode  = @"GuangleHighway";
    GetConstructionEventDetailInfo.MethodName  = @"GetConstructionEventDetailInfo";
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){
        _Model = [EventDetailModel mj_objectWithKeyValues:requestOutginseng.DataValue];
        [self refreshUIData]; //刷新UI数据
    };
    [requestHelper RequestGinsengModel:GetConstructionEventDetailInfo andPushController:self];
}

- (void) setConfig {
    _Model = [[EventDetailModel alloc] init];
    
    _dealTF.delegate  = self;
    _dealTF.scrollEnabled = NO;
    _dealTF.layer.borderColor = [UIColor clearColor].CGColor;
    _dealTF.layer.borderWidth = 0.0;
}
#pragma mark - 加载数据
- (void) refreshUIData {
    _unitsLabel.text            = _Model.Department;
    _headerTF.text              = _Model.Header;
    _contactTF.text             = _Model.Telephone;
    
    NSString *b                 = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.BeginPile];
    NSString *begin             = [b stringByReplacingOccurrencesOfString:@"K" withString:@" "];
    NSString *beginDistance     = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.BeginPileDistance];
    NSString *bd                = [NSString stringWithFormat:@"%@",_Model.EventBaseInfo.EndPile];
    NSString *end               = [bd stringByReplacingOccurrencesOfString:@"K" withString:@" "];
    NSString *endDistance       = [NSString stringWithFormat:@"%ld",(long)_Model.EventBaseInfo.EndPileDistance];
    
    if ([_Model.EventBaseInfo.RoadUID isEqualToString:@"8dd13d88-cb02-4471-876b-1dfe39419ee6"]) {
        UILabel *lab1      = [[UILabel alloc] init];
        lab1.text                 = @"K";
        lab1.frame                = CGRectMake(0, 0, 15, 10);
        lab1.textAlignment        = NSTextAlignmentCenter;
        _beginPileTF.leftView     = lab1;
        _beginPileTF.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.text               = @"K";
        lab2.frame              = CGRectMake(0, 0, 15, 10);
        lab2.textAlignment      = NSTextAlignmentCenter;
        _endPileTF.leftView     = lab2;
        _endPileTF.leftViewMode = UITextFieldViewModeAlways;
        
        //        begin = [b stringByReplacingOccurrencesOfString:@"K" withString:@""];
    } else {
        UILabel *lab1      = [[UILabel alloc] init];
        NSString *LStr     = @"L";
        NSString *KStr     = @"K";
        lab1.font          = [UIFont boldSystemFontOfSize:15];
        lab1.text                 = [LStr stringByAppendingString:KStr];
        lab1.frame                = CGRectMake(0, 0, 30, 10);
//        lab1.textAlignment        = NSTextAlignmentCenter;
        _beginPileTF.leftView     = lab1;
        _beginPileTF.leftViewMode = UITextFieldViewModeAlways;
        
        UILabel *lab2      = [[UILabel alloc] init];
        lab2.font          = [UIFont boldSystemFontOfSize:15];
        lab2.text               = [LStr stringByAppendingString:KStr];
        lab2.frame              = CGRectMake(0, 0, 30, 10);
//        lab2.textAlignment      = NSTextAlignmentCenter;
        _endPileTF.leftView     = lab2;
        _endPileTF.leftViewMode = UITextFieldViewModeAlways;
    }

    
    _beginPileTF.text           = begin;
    _beginPileDistanceTF.text   = beginDistance;
    _endPileTF.text             = end;
    _endPileDistanceTF.text     = endDistance;
    
    _planBeginTimeTF.text       = _Model.EventBaseInfo.OccurTime;
    _planEndTimeTF.text         = _Model.EventBaseInfo.EndTime;
    _projectTF.text             = _Model.Content;
    _RoadDirectionTF.text       = _Model.EventBaseInfo.RoadDerectionName;
    
    if (_Model.EventBaseInfo.TollStationName.length > 0) {
        _mainLineTF.text = @"收费站";
        _isMianLine.text = _Model.EventBaseInfo.TollStationName;
    }else {
        _mainLineTF.text            = _Model.EventBaseInfo.RoadName;
        if (_Model.EventBaseInfo.IsRamp == 0) {
            _isMianLine.text = @"主线";
        }else {
            _isMianLine.text  = @"非主线";
        }
    }
//    _mainLineTF.text            = _Model.EventBaseInfo.RoadName;
//    if (!_Model.EventBaseInfo.IsRamp ) {
//        _isMianLine.text = @"主线";
//    }else {
//    _isMianLine.text  = @"非主线";
//    }
}
//_DataValue	__NSCFString *	@"{\"TypeName\":\"更新数据\",\"State\":0,\"Message\":\"可为空的对象必须具有一个值。\",\"HashResult\":null}"	0x00007fbc31d1bfd0
#pragma mark - 提交修改后的事件
- (void) postDataToServer {
    RequestHelper *requestHelper=[[RequestHelper alloc] init];
    RequestGinsengModel *getCurrentEventModel=[[RequestGinsengModel alloc] init];
    getCurrentEventModel.URL         = GetEventDataURL;
    getCurrentEventModel.DataValue   = [self dataValueString];
    getCurrentEventModel.UpdatedTime = @"2012-01-12 12:00:00";
    getCurrentEventModel.SystemCode  = @"GuangleHighway";
    getCurrentEventModel.MethodName  = @"AddConstructionEventDeal";
    
    requestHelper.block=^(RequestOutginseng *requestOutginseng,id dataValueModel){

        if ([requestOutginseng.Code integerValue] == 001) {
            [SVProgressHUD showSuccessWithStatus:@"上报成功"];
        } else {
            [SVProgressHUD showSuccessWithStatus:@"上报失败"];
            return;
        }
    };
    [self requestTestUpdateImage:getCurrentEventModel Image:_originalImgArr];

}
-(void)requestTestUpdateImage:(RequestGinsengModel *)RequestGinseng Image:(NSArray *)LoadImages {
    
    [SVProgressHUD showWithStatus:@"正在上传,请稍后......"];
    
    NSDictionary *dic=[[NSDictionary alloc] init];
    dic = @{@"methodName":RequestGinseng.MethodName,@"updatedtime":RequestGinseng.UpdatedTime,@"systemcode":DefaultSystemCode,@"DataValue":RequestGinseng.DataValue};
    NSMutableArray *images = [[NSMutableArray alloc] init];
    [images addObjectsFromArray:LoadImages];
    
    //    if (LoadImages.count != 0 ) {
    [BCNetAPIClient PostVideosAndImages:GetEventDataURL parameters:dic imageArray:images videoArray:_videoUrl.absoluteString success:^(id responseObjecet) {
        [SVProgressHUD showSuccessWithStatus:@"成功"];
        [self.navigationController popViewControllerAnimated:YES];
    } failure:^(NSError *error) {
        [SVProgressHUD showSuccessWithStatus:@"失败"];
        [self.navigationController popViewControllerAnimated:YES];
    }];
    //    }
}

#pragma mark - test
- (NSString *)dataValueString {
    
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"IncidentUID\",\"value\":\"%@\"},{\"key\":\"DealDetail\",\"value\":\"%@\"}]",_reportModel.IncidentUID,_dealTF.text];
    return valueStr;
}

#pragma mark - BoPhotoPickerProtocol
- (void)photoPickerDidCancel:(AJPhotoPickerViewController *)picker {
    [picker dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPicker:(AJPhotoPickerViewController *)picker didSelectAssets:(NSArray *)assets {
    [self.photos addObjectsFromArray:assets];
    [picker dismissViewControllerAnimated:NO completion:nil];
    CGFloat x = 0;
    CGRect frame = CGRectMake(0, 0, 125, 125);
    self.imageScrollView.hidden = NO;
    
    if (_originalImgArr.count > 0) {
        [_originalImgArr removeAllObjects];
    }
    _originalImgArr = [[NSMutableArray alloc] init];
    for (int i = 0 ; i < self.photos.count; i++) {
        ALAsset *asset = self.photos[i];
        UIImage *tempImg = [UIImage imageWithCGImage:asset.defaultRepresentation.fullScreenImage];
        frame.origin.x = x;
        UIImageView *imageView = [[UIImageView alloc] initWithFrame:frame];
        [imageView setContentMode:UIViewContentModeScaleAspectFill];
        imageView.clipsToBounds = YES;
        imageView.image = tempImg;
        imageView.tag = i;
        imageView.userInteractionEnabled = YES;
        [imageView addGestureRecognizer:[[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(showBig:)]];
        [_originalImgArr addObject:imageView.image];
        [self.imageScrollView addSubview:imageView];
        x += frame.size.width+5;
        self.imageScrollView.contentSize = CGSizeMake(125 * self.photos.count, 0);
    }
    
}

- (void)showBig:(UITapGestureRecognizer *)sender {
    NSInteger index = sender.view.tag;
    AJPhotoBrowserViewController *photoBrowserViewController = [[AJPhotoBrowserViewController alloc] initWithPhotos:self.photos index:index];
    photoBrowserViewController.delegate = self;
    [self presentViewController:photoBrowserViewController animated:YES completion:nil];
}
- (void)photoBrowser:(AJPhotoBrowserViewController *)vc didDonePhotos:(NSArray *)photos {
    [vc dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoPickerTapCameraAction:(AJPhotoPickerViewController *)picker {
    [self checkCameraAvailability:^(BOOL auth) {
        if (!auth) {
            NSLog(@"没有访问相机权限");
            return;
        }
        [picker dismissViewControllerAnimated:NO completion:nil];
        UIImagePickerController *cameraUI = [UIImagePickerController new];
        cameraUI.allowsEditing   = NO;
        cameraUI.delegate        = self;
        cameraUI.sourceType      = UIImagePickerControllerSourceTypeCamera;
        cameraUI.cameraFlashMode = UIImagePickerControllerCameraFlashModeAuto;
        [self presentViewController: cameraUI animated: YES completion:nil];
    }];
}
- (void)checkCameraAvailability:(void (^)(BOOL auth))block {
    BOOL status = NO;
    AVAuthorizationStatus authStatus = [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeVideo];
    if(authStatus == AVAuthorizationStatusAuthorized) {
        status = YES;
    } else if (authStatus == AVAuthorizationStatusDenied) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusRestricted) {
        status = NO;
    } else if (authStatus == AVAuthorizationStatusNotDetermined) {
        [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
            if(granted){
                if (block) {
                    block(granted);
                }
            } else {
                if (block) {
                    block(granted);
                }
            }
        }];
        return;
    }
    if (block) {
        block(status);
    }
}


- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
    
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage;
    if (CFStringCompare((CFStringRef) mediaType,kUTTypeImage, 0)== kCFCompareEqualTo) {
        originalImage = (UIImage *) [info objectForKey:UIImagePickerControllerOriginalImage];
    }
    
    if (picker.sourceType == UIImagePickerControllerSourceTypeCamera) {
        UIImageWriteToSavedPhotosAlbum(originalImage, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    }else {
        [self dismissViewControllerAnimated:YES completion:nil];
    }
}
- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo {
    if (!error) {
        NSLog(@"保存到相册成功");
        AJPhotoPickerViewController *picker = [[AJPhotoPickerViewController alloc] init];
        picker.maximumNumberOfSelection = 5;
        picker.multipleSelection        = YES;
        picker.assetsFilter             = [ALAssetsFilter allPhotos];
        picker.showEmptyGroups          = YES;
        picker.delegate                 = self;
        picker.selectionFilter          = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
            return YES;
        }];
        [self dismissViewControllerAnimated:NO completion:nil];
        [self presentViewController:picker animated:NO completion:nil];
    }else{
        NSLog(@"保存到相册出错%@", error);
    }
}


// *********** - 播放小视频 - *************
#pragma mark -littleVideoDelegate
- (void)finishLittleVideoViewControllerCapture:(NSURL *)filePath {
    _videoUrl = filePath;
    [self crreatPlayViedeo:filePath];
    
}
- (void) crreatPlayViedeo:(NSURL *)videoUrl {
    _playItem = [AVPlayerItem playerItemWithURL:videoUrl];
    _player = [AVPlayer playerWithPlayerItem:_playItem];
    _playerLayer =[AVPlayerLayer playerLayerWithPlayer:_player];
    _playerLayer.frame = CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width - 16, 200);
    _playerLayer.videoGravity=AVLayerVideoGravityResizeAspectFill;//视频填充模式
    [self.VideoV.layer addSublayer:_playerLayer];
    [_player play];
    //    _isHaveVideo   = YES;
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    [_player pause];
    _player = nil;
    //    [_sheet hiddenSheet];
}



//IncidentUID拼接参数
-(NSString *)getConstructDataValueStr:(NSString *)IncidentUID {
    NSString *valueStr =[NSString stringWithFormat:@"[{\"key\":\"EventUID\",\"value\":\"%@\"}]",IncidentUID];
    return valueStr;
}
@end
